package com.detrum.sportcamera.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.health.SystemHealthManager;
import android.text.format.Formatter;

import com.detrum.base.BaseFinal;
import com.detrum.base.BaseStatic;
import com.detrum.base.ServiceStatic;
import com.detrum.bean.FileBean;
import com.detrum.bean.VersionBean;
import com.detrum.bean.ViewPagerItem;
import com.detrum.sportcamera.R;
import com.detrum.sportcamera.finals.SportStatic;
import com.detrum.sportcamera.finals.WifiFinal;
import com.detrum.sportcamera.nfsnet.NfsManagerCall;
import com.detrum.sportcamera.nfsnet.NfsManagerCall3;
import com.detrum.sportcamera.nfsnet.NfsManagerCall4;
import com.detrum.sportcamera.nfsnet.NfsManagerCall5;
import com.detrum.sportcamera.nfsnet.NfsManagerCall6;
import com.detrum.sportcamera.nfsnet.NfsRequestManager;
import com.detrum.sportcamera.nfstask.NfsDeleteListTask;
import com.detrum.sportcamera.nfstask.NfsDownLoadTask;
import com.detrum.sportcamera.nfstask.NfsGetFiles;
import com.detrum.sportcamera.nfstask.NfsLoadSingle;
import com.detrum.utils.DeviceFinal;
import com.detrum.utils.MyMethod;
import com.detrum.wifidevice.receive.NetStateCall;
import com.detrum.wifidevice.receive.NetStateReceiver;
import com.detrum.sportcamera.runnable.HeartRunnable;
import com.detrum.sportcamera.runnable.MsgRunnable;
import com.detrum.sportcamera.runnable.PreviewCall;
import com.detrum.sportcamera.runnable.PreviewRunnable;
import com.detrum.sportcamera.runnable.ResponseCallBack;
import com.detrum.sportcamera.runnable.SendOrder;
import com.detrum.sportcamera.runnable.SendRunnable;
import com.detrum.sqlite.SqliteDeviceOperate;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.sqlite.SqliteVersionOperate;
import com.detrum.utils.LogUtils;
import com.detrum.wifidevice.WifiObject;
import com.detrum.wifidevice.WifiSacnCall;
import com.detrum.wifidevice.bean.WifiInfoBean;

import java.io.File;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.detrum.base.BaseFinal.dcam;

public class WifiService extends Service implements NetStateCall, ResponseCallBack {
    private Context context;
    private WifiObject wifiObject;
    private WifiManager wifiManager;
    private WifiServiceCallback wifiServiceCallback;
    private WifiServiceCallback2 wifiServiceCallback2;
    private WifiServiceCallback3 wifiServiceCallback3;
    private WifiServiceCallback4 wifiServiceCallback4;
    private WifiServiceCallback5 wifiServiceCallback5;
    private WifiServiceCallback6 wifiServiceCallback6;
    private WifiServiceCallback7 wifiServiceCallback7;
    private WifiInfoBean.DataBean wifiBean;
    private String currentSSID;
    private DatagramSocket receiverSocket, sendSocket;
    private ExecutorService executorService;
    private int threadNum = 4;
    private final int delayTime = 1000;
    private Timer heartTimer;
    private int currentWBMode, currentExposureMode, currentRadiosMode, currentCodeRate,currentRecordPolicy,currentTVMode,currentOSD;

    private int nfsPage = 1;
    private ArrayList<FileBean> list = new ArrayList<>();

    private NetStateReceiver netStateReceiver;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (net == 0) {
                return;
            }
            if (msg.what == 100) {
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.previewFail(WifiFinal.PreviewSocketTimeout);
                    if (receiverSocket != null) {
                        receiverSocket.close();
                        receiverSocket = null;
                    }
                }
                if (wifiServiceCallback4 != null) {
                    wifiServiceCallback4.timeout();
                    if (sendSocket != null) {
                        sendSocket.close();
                        sendSocket = null;
                    }
                }
            } else if (msg.what == 200) {
                if (wifiServiceCallback3 != null) {
                    LogUtils.e("WifiService handler IOException");
                    wifiServiceCallback3.previewFail(WifiFinal.PreviewSocketIOException);
                }
            }

        }
    };

    public void setWifiServiceCallback(WifiServiceCallback wifiServiceCallback) {
        this.wifiServiceCallback = wifiServiceCallback;
    }

    public void setWifiServiceCallback2(WifiServiceCallback2 wifiServiceCallback2) {
        this.wifiServiceCallback2 = wifiServiceCallback2;
    }

    public void setWifiServiceCallback3(WifiServiceCallback3 wifiServiceCallback3) {
        this.wifiServiceCallback3 = wifiServiceCallback3;
    }

    public void setWifiServiceCallback4(WifiServiceCallback4 wifiServiceCallback4) {
        this.wifiServiceCallback4 = wifiServiceCallback4;
    }

    public void setWifiServiceCallback5(WifiServiceCallback5 wifiServiceCallback5) {
        this.wifiServiceCallback5 = wifiServiceCallback5;
    }

    public void setWifiServiceCallback6(WifiServiceCallback6 wifiServiceCallback6) {
        this.wifiServiceCallback6 = wifiServiceCallback6;
    }

    public void setWifiServiceCallback7(WifiServiceCallback7 wifiServiceCallback7) {
        this.wifiServiceCallback7 = wifiServiceCallback7;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        ServiceStatic.isWifiServiceStart = true;
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        wifiObject = new WifiObject();
        executorService = Executors.newFixedThreadPool(threadNum);
        netStateReceiver = new NetStateReceiver(this);
        IntentFilter netIntentFilter = new IntentFilter();
        netIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(netStateReceiver, netIntentFilter);
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogUtils.e("onBind");
        return new WifiBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogUtils.e("onUnbind");

        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.e("onDestroy");
        ServiceStatic.isWifiServiceStart = false;
        SportStatic.isGetFiles = false;
        if (heartTimer != null) {
            heartTimer.cancel();
        }
        unregisterReceiver(netStateReceiver);
        new Thread(new Runnable() {
            @Override
            public void run() {
                NfsRelease();
            }
        }).start();
    }

    private int net;

    @Override
    public void NetState(int status) {
        if (wifiServiceCallback != null) {
            wifiServiceCallback.connectState(status);
        }
        if (status == 1) {
            LogUtils.i("status = " + status + "    net = " + net);
            if (net == 1) {
                return;
            }
            net = 1;
            String SSID = wifiManager.getConnectionInfo().getSSID();
            LogUtils.i("SSID = " + SSID);
            LogUtils.i("currentSSID = " + currentSSID);
            //getIP();//测试获取IP
            if (SSID.equals("\"" + currentSSID + "\"") && !ServiceStatic.isWifiDeviceConnect) {
                getIP();//连接成功只获取IP
                ServiceStatic.isWifiDeviceConnect = true;
                if (wifiServiceCallback != null) {
                    wifiServiceCallback.connectSuccess();
                }
            } else {
                ServiceStatic.isWifiDeviceConnect = false;
            }
        } else if (status == 0) {
            ServiceStatic.isWifiDeviceConnect = false;
            SportStatic.isGetFiles = false;
            SqliteMediaOperation.getInstence(context).UpdataAllNfs(1, 2);
            if (net == 0) {
                return;
            }
            net = 0;
            if (wifiServiceCallback3 != null) {
                wifiServiceCallback3.previewFail(WifiFinal.PreviewSocketTimeout);
            }
            if (wifiServiceCallback4 != null) {
                wifiServiceCallback4.timeout();
            }
            if (wifiServiceCallback2 != null) {
                wifiServiceCallback2.Disconnect();
            }
            if (wifiServiceCallback5 != null) {
                wifiServiceCallback5.Disconnect();
            }
            SportStatic.isLoginPre = false;
            LogUtils.i("wifi断开");
        } else {
            net = status;
            if (wifiServiceCallback != null) {
                wifiServiceCallback.connectState(status);
            }
        }
    }

    private class MemoryManager implements Runnable {
        List<File> fileList;

        public MemoryManager() {
            if (fileList == null) {
                fileList = new ArrayList<>();
            } else {
                fileList.clear();
            }
        }

        public List<File> getList() {
            return fileList;
        }

        @Override
        public void run() {
            ArrayList<FileBean> beans = SqliteMediaOperation.getInstence(context).getDeleteFiles();//获取待删除数据集合
            if (beans != null && beans.size() != 0) {
                for (int i = 0; i < beans.size(); i++) {
                    SqliteMediaOperation.getInstence(context).DeleteItem(beans.get(i).getFileName());//逐一清理数据库数据
                }
            }
            File dirFile = new File(BaseStatic.MediaPath);
            File dirFile2 = new File(BaseStatic.ThumbPath);
            fileList = getFiles(dirFile, fileList);//获取所有缓存媒体文件
            LogUtils.i("fileList size 1 ============ " + fileList.size());
            fileList = getFiles(dirFile2, fileList);//获取所有缓存媒体文件
            LogUtils.i("fileList size 2 ============ " + fileList.size());
            CheckFiles(fileList);//逐一对比删除本地冗余文件
        }
    }

    private List<File> getFiles(File dirFile, List<File> fileList) {
        File[] files = dirFile.listFiles();
        if (files.length == 0) {
            return fileList;
        }
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile() && !fileList.contains(files[i])) {
                LogUtils.i("files = " + files[i].getName());
                fileList.add(files[i]);
            } else if (files[i].isDirectory()) {
                LogUtils.i("Directory = " + files[i].getName());
                fileList.addAll(getFiles(files[i], fileList));
            }
        }
        return fileList;
    }

    private void CheckFiles(List<File> fileList) {
        LogUtils.e("WifiClean size ====================== " + fileList.size());
        for (int i = 0; i < fileList.size(); i++) {
            String fileName = fileList.get(i).getName();
            if (fileName.endsWith(".det")) {
                if (wifiServiceCallback6 != null && !SportStatic.isDownloading) {
                    fileName = fileName.replace(".det", "").trim();
                    int n = SqliteMediaOperation.getInstence(context).SelectFileNum(fileName);
                    if(n <= 0){
                        fileList.get(i).delete();
                    }else{
                        wifiServiceCallback6.reDownload(fileName,fileList.get(i));
                    }
                    continue;
                }
            }
            int num = SqliteMediaOperation.getInstence(context).SelectFileNum(fileName);
            LogUtils.e("WifiClean size ==========" + num + "============ " + fileName);
            if (num <= 0) {
                fileList.get(i).delete();
            }
        }
    }

    /**
     * 获取预览数据
     */
    public void getPreviewData() {
        try {
            if (receiverSocket != null) {
                receiverSocket.close();
                receiverSocket = null;
            }
            receiverSocket = new DatagramSocket(0, Inet4Address.getByName(BaseStatic.DHCP_LOCAL_IP));
            receiverSocket.setSoTimeout(3000);
            SportStatic.RTP_PORT = receiverSocket.getLocalPort();
            executorService.execute(new PreviewRunnable(receiverSocket, handler, new PreviewCall() {
                @Override
                public void receiveData(byte[] bytes, int length) {
                    if (wifiServiceCallback3 != null) {
                        wifiServiceCallback3.receivePreview(bytes, length);
                    }
                }
            }));//预览数据接收
            executorService.execute(new SendRunnable(SendOrder.getStartRtp(), sendSocket));//发送开始预览指令
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止预览
     */
    public void StopPreview() {
        executorService.execute(new SendRunnable(SendOrder.getStopRtp(), sendSocket));//发送停止预览指令
        if (receiverSocket != null) {
            receiverSocket.close();
            receiverSocket = null;
        }
    }

    /**
     * 登录设备
     */
    public void LoginDevice() {
        getIP();
        if (SportStatic.isLoginPre && sendSocket != null) {
            return;
        }
        if (sendSocket != null) {
            sendSocket.close();
            sendSocket = null;
        }
        try {
            sendSocket = new DatagramSocket();
            sendSocket.setSoTimeout(3000);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        executorService.execute(new MsgRunnable(handler, sendSocket, this));//开启指令数据反馈接收
        executorService.execute(new SendRunnable(SendOrder.getLogin(), sendSocket));//发送登录指令
        LogUtils.i("LoginDevice");
    }

    /**
     * 登出设备
     */
    public void LogoutDevice() {
        executorService.execute(new SendRunnable(SendOrder.getLogout(), sendSocket));//发送登出指令
        if (heartTimer != null) {
            heartTimer.cancel();
            heartTimer = null;
        }
    }

    /**
     * 获取码率参数--清晰度
     */
    public void getCodeRate() {
        executorService.execute(new SendRunnable(SendOrder.getCodeRate(), sendSocket));
    }

    /**
     * 设定码率参数--清晰度
     *
     * @param Rate
     */
    public void setCodeRate(int Rate) {
        currentCodeRate = Rate;
        byte[] msgData = {0x00};
        if (Rate == 0) {
            msgData[0] = 0x00;
        } else if (Rate == 1) {
            msgData[0] = 0x01;
        } else if (Rate == 2) {
            msgData[0] = 0x02;
        }
        executorService.execute(new SendRunnable(SendOrder.setCodeRate(msgData), sendSocket));
    }

    /**
     * 获取白平衡参数
     */
    public void getWB() {
        executorService.execute(new SendRunnable(SendOrder.getWbMode(), sendSocket));
    }

    public void setWB(int wbmode) {
        currentWBMode = wbmode;
        byte[] msgData = {0x00, 0x00, 0x00, 0x00};
        if (wbmode == 0) {
            msgData[0] = 0x00;
        } else if (wbmode == 1) {
            msgData[0] = 0x01;
        } else if (wbmode == 2) {
            msgData[0] = 0x02;
        } else if (wbmode == 3) {
            msgData[0] = 0x03;
        } else if (wbmode == 4) {
            msgData[0] = 0x04;
        }
        executorService.execute(new SendRunnable(SendOrder.setWbMode(msgData), sendSocket));
    }

    /**
     * 获取曝光度参数
     */
    public void getExposure() {
        executorService.execute(new SendRunnable(SendOrder.getExporsureMode(), sendSocket));
    }

    /**
     * 设定曝光度参数
     *
     * @param exposuremode
     */
    public void setExposure(int exposuremode) {
        currentExposureMode = exposuremode;
        byte[] msgData = {0x00, 0x00, 0x00, 0x00};
        if (exposuremode == 0) {
            msgData[0] = 0x00;
        } else if (exposuremode == 1) {
            msgData[0] = 0x01;
        } else if (exposuremode == 2) {
            msgData[0] = 0x02;
        } else if (exposuremode == 3) {
            msgData[0] = 0x03;
        } else if (exposuremode == 4) {
            msgData[0] = 0x04;
        } else if (exposuremode == 5) {
            msgData[0] = 0x05;
        } else if (exposuremode == 6) {
            msgData[0] = 0x06;
        } else if (exposuremode == 7) {
            msgData[0] = 0x07;
        } else if (exposuremode == 8) {
            msgData[0] = 0x08;
        } else if (exposuremode == 9) {
            msgData[0] = 0x09;
        } else if (exposuremode == 10) {
            msgData[0] = 0x0A;
        } else if (exposuremode == 11) {
            msgData[0] = 0x0B;
        } else if (exposuremode == 12) {
            msgData[0] = 0x0C;
        } else if (exposuremode == 13) {
            msgData[0] = 0x0D;
        }
        executorService.execute(new SendRunnable(SendOrder.setExposureMode(msgData), sendSocket));
    }

    /**
     * 获取录像分辨率参数
     */
    public void getRatios() {
        executorService.execute(new SendRunnable(SendOrder.getRecordResolution(), sendSocket));
    }

    public void setRatios(int ratiosmode) {
        currentRadiosMode = ratiosmode;
        LogUtils.e("setRatios ratiosmode = " + ratiosmode);
        byte[] msgData = {0x00, 0x00, 0x00, 0x03};
        if (ratiosmode == 1) {
            msgData[3] = 0x01;
        } else if (ratiosmode == 2) {
            msgData[3] = 0x02;
        } else if (ratiosmode == 3) {
            msgData[3] = 0x03;
        } else if (ratiosmode == 4) {
            msgData[3] = 0x04;
        } else if (ratiosmode == 5) {
            msgData[3] = 0x05;
        } else if (ratiosmode == 6) {
            msgData[3] = 0x06;
        }
        executorService.execute(new SendRunnable(SendOrder.setRecordResolution(msgData), sendSocket));
    }

    public void getRecordPolicy(){
        executorService.execute(new SendRunnable(SendOrder.getRecordPolicy(), sendSocket));
    }

    public void setRecordPolicy(int recordPolicy){
        currentRecordPolicy = recordPolicy;
        byte[] msgData = {0x00, 0x00, 0x00, 0x00};
        if(currentRecordPolicy==1){
            msgData[3] = 0x01;
        }else if(currentRecordPolicy==0){
            msgData[3] = 0x00;
        }
        executorService.execute(new SendRunnable(SendOrder.setRecordPolicy(msgData), sendSocket));
    }

    public void getTVMode(){
        executorService.execute(new SendRunnable(SendOrder.getTVMode(), sendSocket));
    }

    public void setTVMode(int tvMode){
        currentTVMode = tvMode;
        byte[] msgData = {0x00, 0x00, 0x00, 0x00};
        if(currentTVMode==1){
            msgData[3] = 0x01;
        }else if(currentTVMode==0){
            msgData[3] = 0x00;
        }
        executorService.execute(new SendRunnable(SendOrder.setTVMode(msgData), sendSocket));
    }

    public void getOSD(){
        executorService.execute(new SendRunnable(SendOrder.getOSDMode(), sendSocket));
    }

    public void setOSD(int osdMode){
        currentOSD = osdMode;
        byte[] msgData = {0x00, 0x00, 0x00, 0x00};
        if(currentOSD==1){
            msgData[3] = 0x01;
        }else if(currentOSD==0){
            msgData[3] = 0x00;
        }
        executorService.execute(new SendRunnable(SendOrder.setOSDMode(msgData), sendSocket));
    }

    //拍照指令
    public void takePicture() {
        executorService.execute(new SendRunnable(SendOrder.getTakePhoto(), sendSocket));
    }

    //开始录像
    public void startVideo() {
        executorService.execute(new SendRunnable(SendOrder.startRecord(), sendSocket));
    }

    //停止录像
    public void stopVideo() {
        executorService.execute(new SendRunnable(SendOrder.stopRecord(), sendSocket));
    }

    //获取存储卡剩余容量
    public void getSDInfo() {
        executorService.execute(new SendRunnable(SendOrder.getSDInfo(), sendSocket));
    }

    /**
     * 获取设备手机的IP地址
     */
    private void getIP() {
        BaseStatic.DHCP_LOCAL_IP = Formatter.formatIpAddress(wifiManager.getDhcpInfo().ipAddress);
        BaseStatic.DHCP_SERVICE_IP = Formatter.formatIpAddress(wifiManager.getDhcpInfo().serverAddress);
        LogUtils.e(BaseStatic.DHCP_LOCAL_IP);
    }

    //录像计时子线程
    private TimeRun timeRun = null;
    private boolean isVideo;

    private class TimeRun implements Runnable {
        private int duration;

        public TimeRun(int dura) {
            duration = dura;
        }

        @Override
        public void run() {
            duration++;
            LogUtils.e("run duration = " + duration);
            LogUtils.e("run wifiServiceCallback3 = " + wifiServiceCallback3);
            if (!isVideo) {
                duration = 0;
                return;
            }
            if (wifiServiceCallback3 != null) {
                wifiServiceCallback3.startVideo(true, duration);
            } else {
                LogUtils.e("run postDelayed = ");
                handler.postDelayed(this, 1000);
            }
        }
    }

    /**
     * 往设备中写文件
     */
    public void WriteUpdateFile() {
        if (SportStatic.isUpdateDevice) {
            return;
        }
        int ret = NfsRequestManager.getInstence(context).UpdateDeviceFile(new NfsManagerCall6() {
            @Override
            public void indexFail() {
                LogUtils.i("WriteUpdateFile indexFail");
                SportStatic.isUpdateDevice = false;
                if (wifiServiceCallback5 != null) {
                    wifiServiceCallback5.indexFail();
                }
            }

            @Override
            public void fileEmpty() {
                SportStatic.isUpdateDevice = false;
                if (wifiServiceCallback5 != null) {
                    // wifiServiceCallback5.updateDevice(0);
                    wifiServiceCallback5.fileEmpty();
                }
            }

            @Override
            public void updateDevice(int position) {
                LogUtils.i("WifiService updateDevice position = " + position);
                SportStatic.isUpdateDevice = true;
                if (position == 2) {
                    executorService.execute(new SendRunnable(SendOrder.upgrade(), sendSocket));
                }
                if (wifiServiceCallback5 != null) {
                    wifiServiceCallback5.updateDevice(position);
                }
            }

            @Override
            public void finish() {
                LogUtils.i("WriteUpdateFile write finish");
            }
        });
        if (ret == -2) {
            LogUtils.i("VersionOperate数据库异常");
        } else if (ret == -3) {
            LogUtils.i("没有安装文件");
        }
    }

    /**
     * 设备数据返回成功
     *
     * @param actionTypes
     * @param response
     */
    @Override
    public void succeed(ActionTypes actionTypes, final byte[] response) {
        switch (actionTypes) {
            case LOGIN://登录
                SportStatic.isLoginPre = true;
                if (wifiServiceCallback2 != null) {
                    wifiServiceCallback2.LoginSuccess();
                }
                if (heartTimer != null) {
                    heartTimer.cancel();
                    heartTimer = null;
                }
                heartTimer = new Timer();
                heartTimer.schedule(new HeartRunnable(sendSocket, handler), delayTime, delayTime);//发送心跳
                executorService.execute(new SendRunnable(SendOrder.getTime(), sendSocket));//发送当前时间
                break;
            case HEART:
                break;
            case SETTIME:
                break;
            case FW_VERSION: //版本信息
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int length3 = response[12];
                        byte[] bytes = new byte[length3];
                        System.arraycopy(response, 13, bytes, 0, length3);
                        String deviceName = new String(bytes);
                        int length2 = response[14 + length3];
                        byte[] bytes2 = new byte[length2];
                        System.arraycopy(response, 15 + length3, bytes2, 0, length2);
                        String deviceVersion = new String(bytes2);
                        ViewPagerItem item = new ViewPagerItem();
                        item.setName(deviceName);
                        item.setMsg(deviceVersion);
                        BaseFinal.CurrentDeviceName = deviceName;
                        if (deviceName.contains("DCAM")) {
                            item.setImage(R.mipmap.sport);
                        }
                        SqliteDeviceOperate.getInstance(context).Insert(item);
                        VersionBean bean = new VersionBean();
                        bean.setDeviceVersion(deviceVersion);
                        bean.setName(deviceName);
                        SqliteVersionOperate.getInstance(context).Insert(bean);
                    }
                }).start();
                break;
            case CUR_STATUS: //录像状态
                int status = response[12];
                if (status == 1) {
                    byte[] time = new byte[4];
                    System.arraycopy(response, 13, time, 0, 4);
                    int a = time[0] << 24 & 0xff000000;
                    int b = time[1] << 16 & 0xff0000;
                    int c = time[2] << 8 & 0xff00;
                    int d = time[3] & 0xff;
                    int duration = a + b + c + d;
                    int xx = time[3] & 0xff;
                    LogUtils.i("xx = " + xx);
                    LogUtils.i("duration = " + duration);
                    if (wifiServiceCallback3 != null) {
                        isVideo = true;
                        wifiServiceCallback3.startVideo(true,duration);
                    }
                    timeRun = new TimeRun(duration);
                    handler.postDelayed(timeRun, 1000);
                } else if (status == 0) {
                    LogUtils.i("status = " + status);
                    if (timeRun != null) {
                        handler.removeCallbacks(timeRun);
                        timeRun = null;
                    }
                    if (wifiServiceCallback3 != null) {
                        isVideo = false;
                        wifiServiceCallback3.stopVideo();
                    }
                    getSDInfo();//停止录像
                }
                break;
            case BAT_REMAIN:
                final int battery = response[15];
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.battery(battery);
                }
                break;
            case START_RTP://开始预览
                SportStatic.isStartPre = true;
                LogUtils.i("START_RTP");
                getSDInfo();//开始预览
                break;
            case STOP_RTP://停止预览
                SportStatic.isStartPre = false;
                if (receiverSocket != null) {
                    receiverSocket.close();
                    receiverSocket = null;
                }
                LogUtils.i("STOP_RTP");
                break;
            case START_RECORD://开始录像
                LogUtils.e("START_RECORD");
               /* if (wifiServiceCallback3 != null) {
                    isVideo = true;
                    wifiServiceCallback3.startVideo(true, 0);
                }*/
                break;
            case STOP_RECORD://停止录像
                LogUtils.e("STOP_RECORD");
                /*if (wifiServiceCallback3 != null) {
                    isVideo = false;
                    wifiServiceCallback3.stopVideo();
                }
                getSDInfo();//停止录像*/
                break;
            case GET_RECORD_POLICY://录像方式
                LogUtils.e("Service GET_RECORD_POLICY currentRecordPolicy = "+currentRecordPolicy);

                /*byte[]POLICY1=new byte[4];
                System.arraycopy(response, 13, POLICY1, 0, 4);
                String stra1 = Arrays.toString(POLICY1);
                LogUtils.i("GET POLICY\n"+stra1);*/

                currentRecordPolicy = response[16];
                if(currentRecordPolicy==1){
                    MyMethod.saveSelectItem(context,new String[]{"recordPolicy"},new boolean[]{true});
                }else if(currentRecordPolicy==0){
                    MyMethod.saveSelectItem(context,new String[]{"recordPolicy"},new boolean[]{false});
                }
                break;
            case SET_RECORD_POLICY://录像方式
                LogUtils.e("Service SET_RECORD_POLICY currentRecordPolicy = "+currentRecordPolicy);

                if(currentRecordPolicy==1){
                    MyMethod.saveSelectItem(context,new String[]{"recordPolicy"},new boolean[]{true});
                }else if(currentRecordPolicy==0){
                    MyMethod.saveSelectItem(context,new String[]{"recordPolicy"},new boolean[]{false});
                }
                break;
            case GET_TV_MODE:

                /*byte[]TV=new byte[4];
                System.arraycopy(response, 13, TV, 0, 4);
                String stra3 = Arrays.toString(TV);
                LogUtils.i("GET_TV\n"+stra3);*/

                currentTVMode = response[16];
                if(currentTVMode==1){
                    MyMethod.saveSingleValue(context,dcam,"tvMode",1);
                }else if(currentTVMode==0){
                    MyMethod.saveSingleValue(context,dcam,"tvMode",0);
                }
                break;
            case SET_TV_MODE:

                byte[]TV1=new byte[4];
                System.arraycopy(response, 13, TV1, 0, 4);
                String stra4 = Arrays.toString(TV1);
                LogUtils.i("SET_TV\n"+stra4);

                break;

            case GET_OSD_MODE:
                currentOSD = response[16];

                /*byte[]OSD=new byte[4];
                System.arraycopy(response, 13, OSD, 0, 4);
                String stra5 = Arrays.toString(OSD);
                LogUtils.i("GET_OSD\n"+stra5);*/

                if(currentOSD==1){
                    MyMethod.saveSelectItem(context,new String[]{"osd"},new boolean[]{true});
                }else if(currentOSD==0){
                    MyMethod.saveSelectItem(context,new String[]{"osd"},new boolean[]{false});
                }
                break;
            case SET_OSD_MODE:

                if(currentOSD==1){
                    MyMethod.saveSelectItem(context,new String[]{"osd"},new boolean[]{true});
                }else if(currentOSD==0){
                    MyMethod.saveSelectItem(context,new String[]{"osd"},new boolean[]{false});
                }
                break;

            case GET_RECORD_QUALITY://码率
                LogUtils.e("Service GET_RECORD_QUALITY");
                currentCodeRate = response[13];
                MyMethod.saveSingleValue(context,dcam,"qxd",currentCodeRate);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.getCodeRate(currentCodeRate);
                }
                break;
            case SET_RECORD_QUALITY://码率
                LogUtils.e("Service SET_RECORD_QUALITY");
                MyMethod.saveSingleValue(context,dcam,"qxd",currentCodeRate);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.setCodeRate(currentCodeRate);
                }
                break;
            case GET_WB_MODE://白平衡
                currentWBMode = response[13];
                LogUtils.i("WifiService currentWbMode = " + currentWBMode);
                MyMethod.saveSingleValue(context,dcam,"wb",currentWBMode);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.getWB(currentWBMode);
                }
                break;
            case SET_WB_MODE://白平衡
                LogUtils.i("WifiService SET_WB_MODE is success");
                MyMethod.saveSingleValue(context,dcam,"wb",currentWBMode);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.setWB(currentWBMode);
                }
                break;
            case GET_EXPOSURE_MODE://曝光度
                currentExposureMode = response[13];
                MyMethod.saveSingleValue(context,dcam,"exposure",currentExposureMode);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.getExposure(currentExposureMode);
                }
                break;
            case SET_EXPOSURE_MODE://曝光度
                LogUtils.i("WifiService SET_EXPOSURE_MODE is success");
                MyMethod.saveSingleValue(context,dcam,"exposure",currentExposureMode);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.setExposure(currentExposureMode);
                }
                break;
            case LOGOUT://登出
                SportStatic.isLoginPre = false;
                LogUtils.e("WifiService Logout");
                break;
            case TAKE_PHOTO://拍照
                final int take = response[13];
                /*Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.camera_click);
                Ringtone r = RingtoneManager.getRingtone(context, uri);
                r.play();
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.captureResponse();
                }*/
                LogUtils.e("WifiService TAKE_PHOTO is success " + take);
                break;
            case GET_RECORD_RESOLUTION://录像分辨率
                currentRadiosMode = response[16];
                MyMethod.saveSingleValue(context,dcam,"ratios",currentRadiosMode);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.getRatios(currentRadiosMode);
                }
                break;
            case SET_RECORD_RESOLUTION://录像分辨率
                MyMethod.saveSingleValue(context,dcam,"ratios",currentRadiosMode);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.setRatios(currentRadiosMode);
                }
                break;
            case PHOTO_NAME://拍照后返回的路径
                Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.camera_click);
                Ringtone r = RingtoneManager.getRingtone(context, uri);
                r.play();
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.captureResponse();
                }
                if (SportStatic.isDownloading) {
                    stopNfsDownload();
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        byte[] pl = new byte[4];
                        System.arraycopy(response, 12, pl, 0, 4);
                        long photoLength = getLength(pl);
                        LogUtils.e("photoLength = " + photoLength);
                        int length = response[16];
                        byte[] byte_name = new byte[length];
                        System.arraycopy(response, 17, byte_name, 0, length);
                        String name = new String(byte_name).trim();
                        LogUtils.e("name = " + name);
                        // TODO: 2018/2/24 拍照后处理
                        long filetime = takePhotoTime(name.substring(0, 14));
                        String nfsPath = DeviceFinal.NFS_FOLDER + "/" + name;
                        String fileName = name;
                        FileBean fileBean = new FileBean();
                        fileBean.setIsNfs(1);
                        fileBean.setNfsPath(nfsPath);
                        fileBean.setFileName(fileName);
                        fileBean.setFileTime(filetime);
                        fileBean.setSize(photoLength);
                        SqliteMediaOperation.getInstence(context).Insert(fileBean);
                    }
                }).start();
                getSDInfo();//得到照片路径
                break;
            case VIDEO_NAME:
                if (SportStatic.isDownloading) {
                    stopNfsDownload();
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        byte[] tt = new byte[2];
                        byte[] ll = new byte[4];
                        int length = response[18];
                        byte[] nn = new byte[length];
                        System.arraycopy(response, 12, tt, 0, 2);
                        System.arraycopy(response, 14, ll, 0, 4);
                        System.arraycopy(response, 19, nn, 0, length);
                        int time = (tt[0] << 8 & 0xff00) + (tt[1] & 0xff);
                        long videoLength = getLength(ll);
                        String videoPath = new String(nn).trim();
                        String videoName = videoPath.split("/")[videoPath.split("/").length - 1];
                        long filetime = takePhotoTime(videoName.substring(0, 14));

                        String nfsPath = videoPath.substring(7);
                        String fileName = videoName;
                        LogUtils.i("-videoName--\n" + videoName + "==nfsPath=" + nfsPath + "\n----");
                        LogUtils.i("-time--\n" + time + "=fileName=" + fileName + "=videoLength=" + videoLength + "\n----");
                        FileBean fileBean = new FileBean();
                        fileBean.setIsNfs(1);
                        fileBean.setNfsPath(nfsPath);
                        fileBean.setFileName(fileName);
                        fileBean.setFileTime(filetime);
                        fileBean.setSize(videoLength);
                        fileBean.setTime(MyMethod.getDateTimeByMillisecond((time - 1) * 1000l, "mm:ss"));
                        SqliteMediaOperation.getInstence(context).Insert(fileBean);
                    }
                }).start();
                getSDInfo();//得到视频路径
                break;
            case D_CAM_DO_UPGRADE: //设备更新结束响应
                SportStatic.isUpdateDevice = false;
                if (wifiServiceCallback5 != null) {
                    wifiServiceCallback5.updateDevice(3);
                }
                VersionBean bean = SqliteVersionOperate.getInstance(context).Select("DCAM-H");
                if (bean == null) {
                    return;
                }
                String filePath = bean.getLocalFilePath();
                File file = new File(filePath);
                if (file.exists()) {
                    LogUtils.i("删除DCAM-H安装文件");
                    file.delete();
                }
                break;
            case GET_SD_INFO:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String sd = Arrays.toString(response);
                        int ret = response[16];
                        if (wifiServiceCallback3 != null) {
                            if (ret == 1) {
                                wifiServiceCallback3.SDSurplus(getSDSave(response));
                            } else if (ret == 0) {
                                wifiServiceCallback3.SDSurplus(0);
                            }
                        }
                        if(wifiServiceCallback2!=null&&ret==0){
                            wifiServiceCallback2.NoCard();
                        }
                    }
                }).start();
                break;
        }
    }

    /**
     * 获取存储卡指令编码
     *
     * @param data
     * @return
     */
    private int getSDSave(byte[] data) {
        byte[] xx = {1, 1, 1, 1};
        int x0 = xx[0] << 24 & 0xff000000;
        int x1 = xx[1] << 16 & 0xff0000;
        int x2 = xx[2] << 8 & 0xff00;
        int x3 = xx[3] & 0xff;
        byte[] cc = new byte[4];
        byte[] ss = new byte[4];
        System.arraycopy(data, 17, cc, 0, 4);
        System.arraycopy(data, 21, ss, 0, 4);
        long count = getLength(cc);
        long surplus = getLength(ss);
        LogUtils.e("count = " + count + "   surplus = " + surplus);
        return (int) (surplus * 100 / count);
    }

    //设备信息转数字
    private long getLength(byte[] data) {
        byte[] xx = {1, 1, 1, 1};
        int x0 = xx[0] << 24 & 0xff000000;
        int x1 = xx[1] << 16 & 0xff0000;
        int x2 = xx[2] << 8 & 0xff00;
        int x3 = xx[3] & 0xff;
        long length = (data[0] & 0xff) * 1l * x0 + (data[1] & 0xff) * 1l * x1 + (data[2] & 0xff) * 1l * x2 + (data[3] & 0xff);
        return length;
    }

    //设备信息转时间戳
    private long takePhotoTime(String name) {
        TimeZone tz = TimeZone.getDefault();
        int offset = tz.getRawOffset();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
        Date date = null;
        try {
            date = format.parse(name);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date == null ? -1 : (date.getTime() + offset) / 1000;
    }

    /**
     * 设备数据返回失败
     *
     * @param actionTypes
     * @param response
     */
    @Override
    public void failed(ActionTypes actionTypes, byte[] response) {
        switch (actionTypes) {
            case LOGIN:
                if (wifiServiceCallback2 != null) {
                    wifiServiceCallback2.LoginFail();
                }
                LogoutDevice();
                break;
            case HEART:
                break;
            case SETTIME:
                break;
            case FW_VERSION:
                break;
            case CUR_STATUS:
                break;
            case START_RTP:
                LogUtils.i("WifiService START_RTP is fail");
                String startFail = Arrays.toString(response);
                LogUtils.i(startFail);
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.previewFail(WifiFinal.PreviewSocketIOException);
                }
                break;
            case STOP_RTP:
                break;
            case START_RECORD:
                LogUtils.i("WifiService START_RECORD is fail");
                if (wifiServiceCallback3 != null) {
                    wifiServiceCallback3.startVideo(false, 0);
                }
                break;
            case STOP_RECORD:
                LogUtils.i("WifiService STOP_RECORD is fail");

                break;
            case GET_WB_MODE:
                LogUtils.i("WifiService GET_WB_MODE is fail");
                break;
            case SET_WB_MODE:
                LogUtils.i("WifiService SET_WB_MODE is fail");
                break;
            case GET_EXPOSURE_MODE:
                LogUtils.i("WifiService GET_EXPOSURE_MODE is fail");
                break;
            case SET_EXPOSURE_MODE:
                LogUtils.i("WifiService SET_EXPOSURE_MODE is fail");
                break;
            case GET_RECORD_RESOLUTION://录像分辨率
                LogUtils.i("WifiService GET_RECORD_RESOLUTION is fail");
                break;
            case SET_RECORD_RESOLUTION:
                LogUtils.i("WifiService SET_RECORD_RESOLUTION is fail");
                break;
            case LOGOUT:
                LogUtils.i("WifiService LOGOUT is fail");
                break;
            case D_CAM_DO_UPGRADE:
                int result = response[12];
                if (result == 0x10) {
                    LogUtils.i("WifiService D_CAM_DO_UPGRADE is fail = RECORD_NO_START");
                } else if (result == 0x11) {
                    LogUtils.i("WifiService D_CAM_DO_UPGRADE is fail = RECORD_NO_PAUSE");
                } else if (result == 0x12) {
                    LogUtils.i("WifiService D_CAM_DO_UPGRADE is fail = RECORDING");
                } else if (result == 0x13) {
                    LogUtils.i("WifiService D_CAM_DO_UPGRADE is fail = NO_UPGRADE_FILE");
                }
                SportStatic.isUpdateDevice = false;
                if (wifiServiceCallback5 != null) {
                    wifiServiceCallback5.installFail();
                }
                break;
            case GET_SD_INFO:
                break;
        }
    }

    public class WifiBinder extends Binder {
        public WifiService getService() {
            return WifiService.this;
        }
    }

    public void setWifiBean(WifiInfoBean.DataBean wifiBean) {
        this.wifiBean = wifiBean;
    }

    public WifiInfoBean.DataBean getWifiBean() {
        return wifiBean;
    }

    //扫描wifi
    public void ScanWifi() {
        wifiObject.ScanWifi(wifiManager, new WifiSacnCall() {
            @Override
            public void scanFail() {
                if (wifiServiceCallback != null) {
                    wifiServiceCallback.scanFail();
                }
            }

            @Override
            public void listResult(String json) {
                if (wifiServiceCallback != null) {
                    wifiServiceCallback.scanResult(json);
                }
            }

        });
    }

    //连接指定wifi
    public void ConnectWifi(String SSID) {
        currentSSID = SSID;
        wifiObject.ConnectWifi(wifiManager, SSID);
        //ConnectStateRun run = new ConnectStateRun();
        //handler.postDelayed(run,1000);
    }

    public void ConnectOldWifi(int id) {
        wifiManager.enableNetwork(id, true);
    }

    NfsGetFiles nfsGetFiles;

    public void getNfsList() {
        getIP();
        if (list == null) {
            list = new ArrayList<>();
        } else {
            list.clear();
        }
        nfsGetFiles = NfsRequestManager.getInstence(context).getNfsFileList(new NfsManagerCall() {
            @Override
            public void getFiles(FileBean bean) {
                if (bean != null) {
                    // LogUtils.i("fileName = " + bean.getNfsPath() + "----------------");
                    list.add(bean);
                    if (wifiServiceCallback4 != null) {
                        wifiServiceCallback4.firstList(bean);
                    }
                    /*if (list.size() == 1 && wifiServiceCallback4 != null) {
                        wifiServiceCallback4.firstList(bean);
                    }*/
                }
            }

            @Override
            public void connectFail() {
                if (wifiServiceCallback4 != null) {
                    wifiServiceCallback4.connectFail();
                }
            }

            @Override
            public void finish() {
                SportStatic.isGetFiles = true;
                if (wifiServiceCallback4 == null) {
                    return;
                }
                if (list.size() == 0) {
                    wifiServiceCallback4.emptyList();
                } else if (list.size() != 0) {
                    wifiServiceCallback4.fileListFinish(list);
                    //
                }
            }
        });
    }

    public void stopGetList() {
        if (nfsGetFiles != null) {
            nfsGetFiles.Stop();
        }
    }

    NfsLoadSingle nfsLoadSingle;

    public void loadNfsSingle(ArrayList<FileBean> fileBeans) {
        LogUtils.i("loadNfsSingle nfsLoadSingle = " + nfsLoadSingle);
        if (nfsLoadSingle != null) {
            nfsLoadSingle.setBeanList(fileBeans);
        } else {
            nfsLoadSingle = NfsRequestManager.getInstence(context).getNfsSingle(fileBeans, new NfsManagerCall3() {
                @Override
                public void indexFail() {
                    LogUtils.i("wifiService indexFail");
                }

                @Override
                public void sendImageStart(FileBean fileBean) {
                    if (wifiServiceCallback4 != null) {
                        wifiServiceCallback4.singleImageStart(fileBean);
                    }
                }

                @Override
                public void sendSingle(FileBean fileBean, int position) {
                    if (wifiServiceCallback4 != null) {
                        wifiServiceCallback4.singleItem(fileBean, position);
                    }
                }

                @Override
                public void avGetFail(FileBean fileBean) {
                    if (wifiServiceCallback4 != null) {
                        wifiServiceCallback4.singleItem(fileBean, fileBean.getPosition());
                    }
                    LogUtils.i("wifiService avGetFail " + fileBean.getFileName());
                }

                @Override
                public void loadfinish() {
                    nfsLoadSingle = null;
                    if (wifiServiceCallback4 != null) {
                        wifiServiceCallback4.singleLoadFinish();
                    }
                }
            });
        }
    }

    public void stopNfsSingle() {
        if (nfsLoadSingle != null) {
            nfsLoadSingle.Stop();
        }
    }

    NfsDownLoadTask downLoadTask;

    public void downloadNfsList(FileBean... fileBeans) {
        downLoadTask = NfsRequestManager.getInstence(context).nfsDownloadList(new NfsManagerCall4() {
            @Override
            public void indexFail() {
                if (wifiServiceCallback6 != null) {
                    wifiServiceCallback6.indexFail();
                }
            }

            @Override
            public void finishAll() {
                if (wifiServiceCallback6 != null) {
                    wifiServiceCallback6.finishAll();
                }
            }

            @Override
            public void itemStart(String fileName, String num) {
                if (wifiServiceCallback6 != null) {
                    wifiServiceCallback6.itemStart(fileName, num);
                }
            }

            @Override
            public void itemComplete(String fileName, String num, int size) {
                if (wifiServiceCallback6 != null) {
                    wifiServiceCallback6.itemComplete(fileName, num, size);
                }
            }

            @Override
            public void itemFail(String fileName) {
                if (wifiServiceCallback6 != null) {
                    wifiServiceCallback6.itemFail(fileName);
                }
            }

            @Override
            public void countSize(int countSize) {
                if (wifiServiceCallback6 != null) {
                    wifiServiceCallback6.countSize(countSize);
                }
            }

            @Override
            public void itemVideoSize(String fileName, String num, int size) {
                if (wifiServiceCallback6 != null) {
                    wifiServiceCallback6.itemVideoSize(fileName, num, size);
                }
            }
        }, fileBeans);

    }

    public void stopNfsDownload() {
        if (downLoadTask != null) {
            downLoadTask.Stop();
        }
    }

    public void stopAnddeleteDownload() {
        if (downLoadTask != null) {
            downLoadTask.Delete();
            downLoadTask.Stop();
        }
    }

    NfsDeleteListTask nfsDeleteListTask;

    public void deleteNfsList(FileBean[] fileBeans) {
        nfsDeleteListTask = NfsRequestManager.getInstence(context).nfsDeleteList(fileBeans, new NfsManagerCall5() {
            @Override
            public void indexFail() {
                if (wifiServiceCallback7 != null) {
                    wifiServiceCallback7.indexFail();
                }
            }

            @Override
            public void itemComplete(String fileName) {
                if (wifiServiceCallback7 != null) {
                    wifiServiceCallback7.itemComplete(fileName);
                }
            }

            @Override
            public void itemFail(String fileName) {
                if (wifiServiceCallback7 != null) {
                    wifiServiceCallback7.itemFail(fileName);
                }
            }

            @Override
            public void finishAll() {
                if (wifiServiceCallback7 != null) {
                    wifiServiceCallback7.finishAll();
                }
                getSDInfo();//文件删除完成
            }
        });
    }

    public void stopNfsDelete() {
        if (nfsDeleteListTask != null) {
            nfsDeleteListTask.Stop();
        }
    }

    public void NfsRefresh(final int nfsFlag) {
        LogUtils.e("WifiService NfsRefresh---" + nfsFlag);
        nfsPage = 1;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                if (nfsFlag == 1) {
                    SqliteMediaOperation.getInstence(context).UpdataAllNfs(3, 1);//将新媒体数据标志3，修改为当前1
                }
                ArrayList<FileBean> fileBeans = SqliteMediaOperation.getInstence(context).SelectNfs(nfsPage, nfsFlag);
                LogUtils.e("WifiService NfsRefresh size = " + fileBeans.size());
                LogUtils.e("WifiService NfsRefresh wifiServiceCallback4 = " + wifiServiceCallback4);
                if (wifiServiceCallback4 != null) {
                    wifiServiceCallback4.refreshList(fileBeans);
                }
            }
        });

    }

    public void NfsLoadMore(final int nfsFlag) {
        nfsPage++;
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<FileBean> fileBeans = SqliteMediaOperation.getInstence(context).SelectNfs(nfsPage, nfsFlag);
                if (wifiServiceCallback4 != null) {
                    wifiServiceCallback4.moreList(fileBeans);
                }
            }
        }).start();
    }

    /**
     * 清理数据库冗余数据和本地多余缓存
     * 先清除标志nfs不为1,且local也不为1的数据库数据
     * 然后获取全部缓存视频文件后逐一对比数据库，不存在的删除。
     */
    public void cleanCache() {
        MemoryManager memoryManager = new MemoryManager();
        new Thread(memoryManager).start();
    }

    public void NfsRelease() {
        SqliteMediaOperation.getInstence(context).UpdataAllNfs(1, 2);
    }
}
